package online_store.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFileServlet extends HttpServlet{
	
	private final String UPLOAD_DIRECTORY = "D:\\uploads"; 
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		//process only if its multipart content
		if(ServletFileUpload.isMultipartContent(request)){
			try{
				DiskFileItemFactory factory = new DiskFileItemFactory();
				List<FileItem> multipart = new ServletFileUpload(factory).parseRequest(request);
				for(FileItem item : multipart){
					if(!item.isFormField()){
						String name = new File(item.getName()).getName();
						item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
					}
				}
				
				out.println("Upload File Successfully!");
				
			}catch(Exception e){
				
				out.println("Upload File Unsuccessfully!");
				
				e.printStackTrace();
			}
		}else{
			out.println("Sorry this Servlet only handles file upload request!");
		}
		
	}
}
